#include <vector>
#include <queue>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
/*
 * @lc app=leetcode.cn id=103 lang=cpp
 *
 * [103] 二叉树的锯齿形层序遍历
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> res;
        deque<TreeNode*> q; q.push_back(root);
        int direction = 1;
        while (!q.empty()) {
            int sz = q.size();
            bool flag = false;
            if (direction) {
                for (int i = 0; i < sz; i++) {
                    auto t = q.front(); q.pop_front();
                    if (!t) continue;
                    q.push_back(t->left); q.push_back(t->right);
                    if (!flag) { res.push_back({t->val}); flag = true;}
                    else res.back().push_back(t->val);
                }
                
            } else {
                for (int i = 0; i < sz; i++) {
                    auto t = q.back(); q.pop_back();
                    if (!t) continue;
                    q.push_front(t->right); q.push_front(t->left);
                    if (!flag) { res.push_back({t->val}); flag = true;}
                    else res.back().push_back(t->val);
                }
            }
            direction = 1 - direction;
        }
        return res;
    }
};
// @lc code=end

